#include "ahxgwnet.h"
using namespace ahxgwnet;

/*
void strCli(FILE *fp, int s)
{
    char        sendBuf[MAXLINE], recvBuf[MAXLINE];
    IOWrapper   iow(s);
    
    while (fgets(sendBuf, MAXLINE, fp) != NULL)
    {
        int nWrite = iow.writeN(sendBuf, 1);
        fprintf(stdout, "nWrite = %d\n", nWrite);
        nWrite = iow.writeN(sendBuf + 1, strlen(sendBuf) - 1);
        fprintf(stdout, "nWrite = %d\n", nWrite);
        if (iow.readLine(recvBuf, MAXLINE) == 0)
        {
            perror("strCli : server abort");
            exit(1);
        }
        fputs(recvBuf, stdout);
    }
}
*/

void strCli(FILE *fp, int s)
{
    int         maxFd;
    fd_set      rSet;
    char        sendBuf[MAXLINE], recvBuf[MAXLINE];
    IOWrapper   iow(s);
    bool        stdinEOF;
    
    FD_ZERO(&rSet);
    stdinEOF = 0;
    for ( ; ; )
    {
        if (!stdinEOF)
            FD_SET(fileno(fp), &rSet);
        FD_SET(s, &rSet);
        maxFd = std::max(fileno(fp), s) + 1;
        select(maxFd, &rSet, NULL, NULL, NULL);
        
        if (FD_ISSET(s, &rSet))
        {
            if (iow.readLine(recvBuf, MAXLINE) == 0)
            {
                if (stdinEOF)
                    return;
                perror("strCli : server abort");
                exit(1);
            }
            fputs(recvBuf, stdout);
        }
        
        if (FD_ISSET(fileno(fp), &rSet))
        {
            if (fgets(sendBuf, MAXLINE, fp) == NULL)
            {
                stdinEOF = 1;
                shutdown(s, SHUT_WR);
                FD_CLR(fileno(fp), &rSet);
//                fprintf(stderr, "any key to continue\n");
//                sleep(10);
                continue;
            }
            iow.writeN(sendBuf, 1);
            sleep(1);
            iow.writeN(sendBuf + 1, strlen(sendBuf) - 1);
        }
    }
}

int main()
{
    Socket  s[15];
    Util    util;
    
    util.signal(SIGPIPE, SIG_IGN);
    
    for (int i = 0; i < 1; i++)
        if (!s[i].connect("127.0.0.1", 8888))
            perror("connect error");
    
    strCli(stdin, s[0].m_s);
    
    return 0;
}
